﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using MLM.Data;

namespace MLM.AdminCP.Pages
{
    public partial class BonusPayingManager : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string SetPaidStatus(string listOfUserId)
        {
            var returnString = "";
            if (!string.IsNullOrEmpty(listOfUserId))
            {
                MLMDataContext ct = new MLMDataContext();
                var ids = listOfUserId.Split(';');
                foreach (var id in ids)
                {
                    if (id != "")
                    {
                        long userId = long.Parse(id.Replace(";", ""));
                        ct.BonusPayings.AddObject(new Data.BonusPaying
                                                      {
                                                          Month = DateTime.Now.Month,
                                                          Year = DateTime.Now.Year,
                                                          UserID = userId,
                                                          Status = 1
                                                      });
                        ct.SaveChanges();
                        returnString += id + "-";
                    }
                }
            }
            return returnString;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string CalculateBonusThisMonth(string _pageIndex, string _pageSize)
        {
            int pageIndex = int.Parse(_pageIndex);
            int pageSize = int.Parse(_pageSize);
            ResponseData responseData = new ResponseData();
            List<BonusPaying> bonusPayings = new List<BonusPaying>();

            var currentMonth = DateTime.Now.Month;
            var minDate = new DateTime(DateTime.Now.Year, currentMonth, 1, 0, 0, 0);
            var maxDate = new DateTime(DateTime.Now.Year, currentMonth,
                                       DateTime.DaysInMonth(DateTime.Now.Year, currentMonth), 23, 59, 0);
            MLMDataContext ct = new MLMDataContext();
            responseData.TotalRow = ct.Users.Count();
            var listUsers = ct.Users.OrderBy(it => it.UserId).Skip(pageIndex * pageSize - pageSize).Take(pageSize);
            if (listUsers.Count() > 0)
            {
                foreach (var user in listUsers)
                {
                    var sponsorList = ct.Users.Where(it => it.SponsorID == user.UserId).ToList();
                    var mySell =
                        ct.Invoices.Where(
                            it =>
                            it.DepoID == user.UserId && it.DateTimeCreated >= minDate && it.DateTimeCreated <= maxDate && it.Status == 1);
                    long? myPoint = 0;
                    long? myOwnPoint = 0;
                    foreach (var invoice in mySell)
                    {
                        var invoiceDetails = ct.InvoiceDetails.Where(it => it.InvoiceID == invoice.InvoiceID);
                        foreach (var invoiceDetail in invoiceDetails)
                        {
                            myPoint += invoiceDetail.Point * invoiceDetail.Quantity;
                            myOwnPoint += invoiceDetail.Point * invoiceDetail.Quantity;
                        }
                    }
                    //sponsor

                    List<MySponsorSelling> sponsorSellings = new List<MySponsorSelling>();
                    foreach (var sponsor in sponsorList)
                    {
                        long sponsorPoint = 0;
                        MySponsorSelling sponsorSelling = new MySponsorSelling();
                        foreach (var item in ct.Invoices.Where(p => p.UserID == sponsor.UserId && p.Status != -1 && p.DateTimeCreated >= minDate && p.DateTimeCreated <= maxDate))
                        {
                            var _point = ct.InvoiceDetails.Where(p => p.InvoiceID == item.InvoiceID);
                            if (_point.Count() > 0)
                            {
                                foreach (var a in _point)
                                {
                                    sponsorPoint += long.Parse(a.Point.ToString()) * long.Parse(a.Quantity.ToString());
                                }
                            }
                        }
                        sponsorSelling.Point = sponsorPoint;
                        sponsorSelling.Bonus = ct.Ranks.Where(it => it.MinPV <= sponsorPoint).Max(it => it.Bonus);
                        myPoint += sponsorPoint;
                    }
                    var myBonus = ct.Ranks.Where(it => it.MinPV <= myPoint).Max(it => it.Bonus);
                    if (myBonus > 0)
                    {
                        BonusPaying bonusPaying = new BonusPaying();
                        bonusPaying.UserId = user.UserId;
                        bonusPaying.Name = user.FirstName + " " + user.LastName;
                        bonusPaying.CurrentBonus += double.Parse((myOwnPoint * myPoint / 100).ToString());//pv
                        foreach (var mySponsorSelling in sponsorSellings)
                        {
                            var difference = myBonus - mySponsorSelling.Bonus;
                            if (difference > 0)
                            {
                                bonusPaying.CurrentBonus += double.Parse((difference * mySponsorSelling.Point / 100).ToString());
                            }
                        }
                        bonusPaying.PaidStatus =
                            ct.BonusPayings.Count(
                                it =>
                                it.UserID == user.UserId && it.Year == DateTime.Now.Year && it.Month == currentMonth && it.Status == 1) >
                            0
                                ? 1
                                : 0;
                        bonusPayings.Add(bonusPaying);
                    }
                    else
                    {
                        var fullname = user.FirstName + " " + user.LastName;
                        var paid =
                           ct.BonusPayings.Count(
                               it =>
                               it.UserID == user.UserId && it.Year == DateTime.Now.Year && it.Month == currentMonth && it.Status == 1) >
                           0
                               ? 1
                               : 0;
                        bonusPayings.Add(new BonusPaying
                                              {
                                                  CurrentBonus = 0,
                                                  Name = fullname,
                                                  PaidStatus = paid,
                                                  UserId = user.UserId
                                              });
                    }
                }
            }
            JavaScriptSerializer ser = new JavaScriptSerializer();
            responseData.Data = bonusPayings;
            return ser.Serialize(responseData);
        }
        public class ResponseData
        {
            public int TotalRow { get; set; }
            public List<BonusPaying> Data { get; set; }
        }
        public class BonusPaying
        {
            public long UserId { get; set; }
            public string Name { get; set; }
            public double CurrentBonus { get; set; }
            public int PaidStatus { get; set; }
        }
        public class MySponsorSelling
        {
            public long Point;
            public int? Bonus;
        }
    }
}